#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
将数据库中的合约信息导出为Python配置文件

用法:
    python scripts/export_contracts_config.py
"""

import os
import sys
import logging
from pathlib import Path
from datetime import datetime
from sqlalchemy import select

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from models.base import get_db_session
from models.contract import Contract

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def fetch_contracts():
    """从数据库获取所有合约信息"""
    session = get_db_session()
    try:
        query = select(Contract).where(Contract.is_active == True)
        contracts = session.execute(query).scalars().all()
        logger.info(f"从数据库获取了 {len(contracts)} 个合约信息")
        return contracts
    except Exception as e:
        logger.error(f"获取合约信息时发生错误: {e}")
        return []
    finally:
        session.close()

def generate_config_file(contracts):
    """生成配置文件内容"""
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    content = [
        "#!/usr/bin/env python",
        "# -*- coding: utf-8 -*-",
        "\"\"\"",
        f"合约配置文件 - 自动生成于 {now}",
        "",
        "此文件由 scripts/export_contracts_config.py 自动生成",
        "请勿手动修改",
        "\"\"\"",
        "",
        "# 合约配置字典，格式: {exchange: {symbol: {配置}}",
        "CONTRACTS = {",
    ]
    
    # 按交易所分组
    exchange_groups = {}
    for contract in contracts:
        if contract.exchange not in exchange_groups:
            exchange_groups[contract.exchange] = []
        exchange_groups[contract.exchange].append(contract)
    
    # 生成配置字典内容
    for exchange, exchange_contracts in exchange_groups.items():
        content.append(f"    # {exchange} 交易所")
        content.append(f"    \"{exchange}\": {{")
        
        for contract in exchange_contracts:
            symbol = contract.symbol
            content.append(f"        \"{symbol}\": {{")
            content.append(f"            \"mark_price_round\": {contract.mark_price_round},")
            content.append(f"            \"quanto_multiplier\": {contract.quanto_multiplier},")
            content.append("        },")
        
        content.append("    },")
    
    content.append("}")
    content.append("")
    
    # 添加辅助函数
    content.extend([
        "def get_contract_info(exchange, symbol):",
        "    \"\"\"获取指定交易所和交易对的合约信息\"\"\"",
        "    return CONTRACTS.get(exchange, {}).get(symbol)",
        "",
        "def get_mark_price_round(exchange, symbol):",
        "    \"\"\"获取价格精度\"\"\"",
        "    contract = get_contract_info(exchange, symbol)",
        "    if contract:",
        "        return contract.get('mark_price_round')",
        "    return None",
        "",
        "def get_quanto_multiplier(exchange, symbol):",
        "    \"\"\"获取合约乘数\"\"\"",
        "    contract = get_contract_info(exchange, symbol)",
        "    if contract:",
        "        return contract.get('quanto_multiplier')",
        "    return None",
        "",
        "def is_contract_active(exchange, symbol):",
        "    \"\"\"检查合约是否活跃\"\"\"",
        "    contract = get_contract_info(exchange, symbol)",
        "    if contract:",
        "        return contract.get('is_active', False)",
        "    return False",
        "",
        "def get_all_symbols(exchange=None):",
        "    \"\"\"获取所有交易对符号\"\"\"",
        "    if exchange:",
        "        return list(CONTRACTS.get(exchange, {}).keys())",
        "    else:",
        "        symbols = []",
        "        for exchange_contracts in CONTRACTS.values():",
        "            symbols.extend(exchange_contracts.keys())",
        "        return symbols",
        "",
    ])
    
    return "\n".join(content)

def save_config_file(content):
    """保存配置文件到config目录"""
    # 确保config目录存在
    config_dir = project_root / "config"
    if not config_dir.exists():
        config_dir.mkdir(parents=True)
        logger.info(f"创建目录: {config_dir}")
    
    # 保存配置文件
    config_file = config_dir / "contracts_config.py"
    with open(config_file, "w", encoding="utf-8") as f:
        f.write(content)
    
    logger.info(f"合约配置已保存到: {config_file}")

def main():
    """主函数"""
    logger.info("开始导出合约配置...")
    
    # 获取合约信息
    contracts = fetch_contracts()
    if not contracts:
        logger.error("未找到合约信息，请确保数据库中有活跃的合约记录")
        return
    
    # 生成配置文件内容
    content = generate_config_file(contracts)
    
    # 保存配置文件
    save_config_file(content)
    
    logger.info("合约配置导出完成")

if __name__ == "__main__":
    main() 